<template>
  <div class="form">
    <el-text>忘记密码</el-text>
    <el-form :model="form" label-width="auto" style="max-width: 600px;margin: auto;">

      <el-form-item>
        <el-button @click="back">返回登录</el-button>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="新密码">
        <el-input type="password" v-model="form.password" />
      </el-form-item>
      <el-form-item label="确认新密码">
        <el-input type="password" v-model="form.confirmPassword" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit(form)">提交</el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>

import { reactive,ref } from "vue";
import loginApi from "@/apis/login";
import { ElNotification } from "element-plus";
import { useRouter } from "vue-router"

const router = useRouter();

let form = reactive({
  phone: '',
  password: '',
  confirmPassword: ''
})

let response;

const onSubmit = async (form) => {
  let data = ref('');
  if(form.password === form.confirmPassword){
    data = {
      phone: form.phone,
      password: form.password
    }
    // console.log(data)
    response = await loginApi.resetPassword(data);
    // console.log(response)
    if(response.code!==200){
      phoneError()
    }else {
      successNotify()
      await router.push({name: 'Login'});
    }
  }else {
    passwordError()
  }

}

const reset = () => {
  form.phone = '';
  form.password = '';
  form.confirmPassword = '';
}

const back = () =>{
  router.push({name: 'Login'});
}

const successNotify = () => {
  ElNotification({
    title: '成功提示',
    message: '修改密码成功',
    type: 'success',
  })
}

const phoneError = () => {
  ElNotification({
    title: '错误提示',
    message: '重置密码失败，请检查手机号是否正确',
    type: 'error',
  })
}

const passwordError = () => {
  ElNotification({
    title: '错误提示',
    message: '重置密码失败，请检查密码是否一致',
    type: 'error',
  })
}
</script>

<style scoped>

</style>
